package com.notebad.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.notebad.R;
import com.notebad.note.Note;
import com.notebad.note.NotesDbManager;
import com.notebad.tools.FileUtilities;

public class TextEditerView extends Activity {
	
	private static final String TAG = "[TextEditerView]";

	private EditText mTitleText;
    private EditText mBodyText;
    private Spinner mCategText;
    private NotesDbManager mDbHelper;
    
    private static final int SAVE_ID = 1;
    private static final int DELETE_ID = SAVE_ID + 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new NotesDbManager(this);
        setContentView(R.layout.note_edit);
        
        mTitleText = (EditText) findViewById(R.id.titleTextView);
        mBodyText = (EditText) findViewById(R.id.bodyTextView);
        mCategText = (Spinner) findViewById(R.id.categoryTextView);
        mDbHelper.open();
        
        if(mDbHelper.getCategories().getCount() == 0)
        {
            //TODO remove these lines when there is the category manager activity
        	mDbHelper.addCategory("Professionel");
        	mDbHelper.addCategory("Personnel");
        	mCategText.setEnabled(false);
        }
        else{

        	Cursor curs= mDbHelper.getCategories();
        	startManagingCursor(curs);

        	List<String> cate = new ArrayList<String>();
        	if (curs != null) {
        		while(curs.moveToNext()){
        			cate.add(curs.getString(curs.getColumnIndexOrThrow(NotesDbManager.KEY_CAT_NAME)));
        		}
        	}
        	if (curs != null)
        		curs.close();

        	ArrayAdapter<CharSequence> m_adapterForSpinner = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);        
        	m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        	mCategText.setAdapter(m_adapterForSpinner);
        	for (String string : cate) {
        		m_adapterForSpinner.add(string);
        	}
        	mCategText.setEnabled(true);
        }
    	mDbHelper.close();
    }
    
    /**
     * Fill fields
     */
    private void populateFields() {
    	Note note = Note.getCurrentNote();
        if (!note.isNew()) {
            mTitleText.setText(note.getTitle());
            mBodyText.setText(note.getBody());
            //TODO set text with database
//            mCategText.setText(note.getCategory());
        }
        else 
        {
        	//TODO set text with un truc empty
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
//        outState.putLong(NotesDbManager.KEY_ROWID, mRowId);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Note.getCurrentNote().setTitle(mTitleText.getText().toString());
        Note.getCurrentNote().setBody(mBodyText.getText().toString());
        Note.getCurrentNote().setBody((String)mCategText.getSelectedItem());
//        saveState();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }
    
    @Override
    protected void onStart() {
    	super.onStart();
        if(Note.getCurrentNote().wasFolderRemoved()){
        	AlertDialog.Builder builder = new AlertDialog.Builder(TextEditerView.this);
			builder.setMessage("Info :\nThis note folder has been deleted.\n" +
					"Sounds and pictures have been lost.")
			.setCancelable(false)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
				}
			});
			AlertDialog alert = builder.create();
			alert.show();
			Note.getCurrentNote().setwasFolderRemoved(false);
        }
    }
    
    private void saveState() {
    	Note.getCurrentNote().setTitle(mTitleText.getText().toString());
    	Note.getCurrentNote().setBody(mBodyText.getText().toString());
        Note.getCurrentNote().setBody((String)mCategText.getSelectedItem());

        if (Note.getCurrentNote().isNew()) {
            mDbHelper.open();
            Note.getCurrentNote().setId(mDbHelper.createNote(Note.getCurrentNote()));
            mDbHelper.close();
            Note.getCurrentNote().save();
            
        } else {
            mDbHelper.open();
            mDbHelper.updateNote(Note.getCurrentNote());
            mDbHelper.close();
        }
    }
    
     @Override
      public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, SAVE_ID, 0, R.string.save_menu).setIcon(R.drawable.ic_menu_save);
		return true;
      }
      
      public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
          case SAVE_ID:
      		if(mTitleText.getText().toString().equals(""))
    		{
    			Log.d(TAG, mTitleText.getText().toString());
    		    AlertDialog alertDialog = new AlertDialog.Builder(TextEditerView.this).create();
    		    alertDialog.setTitle("Le titre n'est pas specifie");
    		    alertDialog.setMessage("Le titre est necessaire pour l'enregistrement");
    		    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
    		      public void onClick(DialogInterface dialog, int which) {
    		        return;
    		    } });
    		    alertDialog.show();
    			return false;
    		}
      		else
      		{
        	  this.saveState();
              return true;
      		}
          case DELETE_ID:
			mDbHelper.open();
			mDbHelper.deleteNote(Note.getCurrentNote().getId());
			mDbHelper.close();
			File tmp = new File(Note.getCurrentNote().getBaseFolder());
			if(tmp.exists()){
				FileUtilities.deleteDirectory(tmp);
			}
			Note.clearCurrentNote();
			startActivity(new Intent(this, NoteListView.class));
			return true;
          }
          return false;
      }
      

	@Override
	public boolean onPrepareOptionsMenu(Menu menu){
		super.onPrepareOptionsMenu(menu);
		if(!Note.getCurrentNote().isNew()){
			menu.add(0, DELETE_ID, 1, R.string.menu_delete).setIcon(R.drawable.ic_menu_delete);
		}
		return true;
	}
    
}
